package com.pmcc.platform.user.service;

import com.alibaba.fastjson.JSONObject;
import com.pmcc.platform.salesman.entity.Salesman;
import com.pmcc.platform.salesman.repository.SalesmanRepository;
import com.pmcc.platform.shopping.entity.Shopping;
import com.pmcc.platform.shopping.entity.ShoppingApply;
import com.pmcc.platform.shopping.repository.ShoppingApplyRepository;
import com.pmcc.platform.shopping.repository.ShoppingRepository;
import com.pmcc.platform.user.entity.Message;
import com.pmcc.platform.user.entity.MinSalesmanUserInfo;
import com.pmcc.platform.user.entity.MinShoppingUserInfo;

import com.pmcc.platform.user.repository.MessageRepository;
import com.pmcc.platform.user.repository.MinSalesmanUserInfoRepository;
import com.pmcc.platform.user.repository.MinShoppingUserInfoRepository;
import com.pmcc.platform.user.repository.UserInfoRepository;
import com.pmcc.utils.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.HashMap;
import java.util.List;

@Slf4j
@Service
@Transactional
public class MessageService {

    @Autowired
    MessageRepository messageRepository;

    @Autowired
    UserInfoRepository userInfoRepository;

    @Autowired
    MinShoppingUserInfoRepository minUserInfoRepository;

    @Autowired
    ShoppingRepository shoppingRepository;

    @Autowired
    ShoppingApplyRepository shoppingApplyRepository;

    @Autowired
    SalesmanRepository salesmanRepository;

    @Autowired
    MinSalesmanUserInfoRepository minSalesmanUserInfoRepository;

    public ApiResultBean smsValidation(String messageType, String phone, String deviceId) {
        ApiResultBean apiResultBean = new ApiResultBean();
        // 短信接口，发送验证码
        String verifyCode = "";
        String sendState = null;
        // 注册模板中的 需要传入 code 参数名称
        String code = SystemPropertyUtil.getProperty("SMSTemplate1ParamKey1");
        JSONObject js = new JSONObject();
        verifyCode = RandomUtils.createRandom(6);
        // 该参数 根据 模板的类型调节
        js.put(code, verifyCode);

        //提现验证一分钟内只能发送一次
        if (true) {
            long time = 1 * 60 * 1000;//1分钟
            Date now = new Date();
            Date beforeDate = new Date(now.getTime() - time);//1分钟前的时间
            List<Message> list = messageRepository.findByTelephoneAndMessageTypeAndStatusAndMessageSendTimeAfter(phone, messageType, "1", beforeDate);
            if (list != null && list.size() > 0) {
                long a = now.getTime();
                long b = list.get(0).getMessageSendTime().getTime();
                int c = 60 - (int) ((a - b) / 1000);
                apiResultBean.setCode(ResultBean.SUCCESS);
                apiResultBean.setMsg("发送频繁，请" + c + "秒后再次发送！");
                apiResultBean.setCode("0");
                return apiResultBean;
            }
        }
        //发送短信
        sendState = AliSmsClient.sendMessage(messageType, js.toString(), phone);

        //将之前短信置为删除状态，防止之前的短信还能用
        List<Message> list = messageRepository.findByTelephoneAndMessageTypeAndStatus(phone, messageType, "1");
        if (list != null && list.size() > 0) {
            list.get(0).setStatus("2");
            messageRepository.save(list.get(0));
        }


        //短信记录
        if (("OK").equals(sendState)) {
            Message message = new Message();
            message.setTelephone(phone);//手机号码
            message.setMessageType(messageType);//短信类型
            message.setMessageContent(verifyCode);//短信内容
            message.setMessageSendTime(new Date());//短信发送时间
            message.setDeviceId(deviceId);//设备 ID
            message.setSendStatus(sendState);
            message.setStatus("1");
            messageRepository.save(message);
            apiResultBean.setCode(ResultBean.SUCCESS);
            apiResultBean.setMsg("验证码已发送");
        } else {
            apiResultBean.setCode(ResultBean.FAIL);
            apiResultBean.setMsg(sendState);
        }
        return apiResultBean;
    }

    /**
     * 根据手机号和验证码判断
     *
     * @param phone       手机号
     * @param content     验证码
     * @param messageType 短信类型
     * @return
     */
    public ApiResultBean miniShoppingCheck(String phone, String content, String messageType, String miniUserId) {
        ApiResultBean apiResultBean = new ApiResultBean();

        //根据手机号查找是否存在记录
        List<Message> list = messageRepository.findByTelephoneAndMessageContentAndMessageTypeAndStatus(phone, content, messageType, "1");
        if (list != null && list.size() > 0) {
            //判断验证码是否过期
            if (new Date().getTime() - list.get(0).getMessageSendTime().getTime() <= CommonVariables.verifyCode_validTime) {
                List<Shopping> shoppings = shoppingRepository.findAllByPhoneAndDelFlag(phone, "0");
                MinShoppingUserInfo minUserInfo = minUserInfoRepository.findOne(miniUserId);
                HashMap<String, String> hashMap = new HashMap<>();
                if (shoppings.size() > 0) {
                    shoppings.get(0).setMiniUserId(miniUserId);
                    minUserInfo.setIsApplication("0");
                    minUserInfo.setShoppingId(shoppings.get(0).getId());
                    minUserInfo.setPhone(phone);
                    minUserInfoRepository.saveAndFlush(minUserInfo);

                    apiResultBean.setData(minUserInfo);
                    apiResultBean.setMsg("登录成功");
                    return apiResultBean;
                } else {
                    List<ShoppingApply> shoppingApplies = shoppingApplyRepository.findAllByPhoneAndDelFlag(phone, "0");
                    if (shoppingApplies.size() > 0) {

                        minUserInfo.setIsApplication("2");
                    } else {
                        minUserInfo.setIsApplication("1");
                        apiResultBean.setMsg("请申请店铺");
                    }
                    minUserInfo.setPhone(phone);

                    apiResultBean.setCode(ApiResultBean.SUCCESS);
                    apiResultBean.setData(minUserInfo);
                    return apiResultBean;
                }

            } else {
                apiResultBean.setCode(ApiResultBean.FAIL);
                apiResultBean.setMsg("验证码已过期");
                return apiResultBean;
            }


        } else {
            apiResultBean.setCode(ApiResultBean.FAIL);
            apiResultBean.setMsg("验证码不正确");
            return apiResultBean;
        }

    }

    public ApiResultBean miniSalesmanCheck(String phone, String content, String messageType, String minSalesamnUserId) {
        ApiResultBean apiResultBean = new ApiResultBean();
        if (StringUtil.isEmpty(minSalesamnUserId)) {
            apiResultBean.setMsg("参数错误");
            apiResultBean.setCode(ApiResultBean.FAIL);
            return apiResultBean;
        }

        //根据手机号查找是否存在记录
        List<Message> list = messageRepository.findByTelephoneAndMessageContentAndMessageTypeAndStatus(phone, content, messageType, "1");
        if (list != null && list.size() > 0) {
            //判断验证码是否过期
            if (new Date().getTime() - list.get(0).getMessageSendTime().getTime() <= CommonVariables.verifyCode_validTime) {

                List<Salesman> salesmen = salesmanRepository.findAllByPhoneAndDelFlag(phone, "0");
                if (salesmen.size() > 0) {
                    MinSalesmanUserInfo minSalsemanUserInfo = minSalesmanUserInfoRepository.findOne(minSalesamnUserId);
                    salesmen.get(0).setMinSalesmanUserId(minSalsemanUserInfo.getId());
                    salesmanRepository.saveAndFlush(salesmen.get(0));
                    minSalsemanUserInfo.setSalesmanId(salesmen.get(0).getId());
                    apiResultBean.setData(minSalsemanUserInfo);
                    return apiResultBean;

                } else {
                    apiResultBean.setCode(ApiResultBean.FAIL);
                    apiResultBean.setMsg("你还未成为业务员");
                    return apiResultBean;
                }
            } else {
                apiResultBean.setCode(ApiResultBean.FAIL);
                apiResultBean.setMsg("验证码错误");
                return apiResultBean;
            }
        }

        return apiResultBean;


    }
}